from django.shortcuts import get_object_or_404
from rest_framework import generics, permissions, status
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Review, ReviewPhoto
from .serializers import ReviewImageUploadSerializer, ReviewPhotoSerializer, ReviewSerializer, ReviewCreateSerializer
from .permissions import IsReviewOwnerOrReadOnly  
from django.db.models import Q

class ReviewCreateView(generics.CreateAPIView):
    queryset = Review.objects.all()
    serializer_class = ReviewCreateSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer):
        order = serializer.validated_data['order']
        serializer.save(
            customer=self.request.user,
            chef=order.chef
        )

class ReviewListView(generics.ListAPIView):
    serializer_class = ReviewSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    filterset_fields = ['chef', 'overall_rating', 'is_public']
    ordering_fields = ['created_at', 'overall_rating']
    ordering = ['-created_at']

    def get_queryset(self):
        queryset = Review.objects.filter(is_public=True)
        
        # 厨师查看自己的评价
        if hasattr(self.request.user, 'chef_profile'):
            return queryset.filter(chef=self.request.user.chef_profile)
            
        # 用户查看自己发表的评价
        if self.request.user.is_authenticated:
            return queryset.filter(customer=self.request.user)
            
        return queryset

class ReviewDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Review.objects.all()
    serializer_class = ReviewSerializer
    permission_classes = [IsReviewOwnerOrReadOnly]

    def perform_update(self, serializer):
        instance = serializer.save()
        # 更新厨师评分
        instance.update_chef_rating()

class ReviewImageUploadView(APIView):
    permission_classes = [permissions.IsAuthenticated]
    
    def post(self, request):
        serializer = ReviewImageUploadSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 保存图片并关联到评价
        review = get_object_or_404(Review, id=serializer.validated_data['review_id'])
        if review.customer != request.user:
            return Response(
                {'error': '无权操作此评价'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        photo = ReviewPhoto.objects.create(
            review=review,
            image=serializer.validated_data['image'],
            uploaded_by=request.user
        )
        
        return Response(
            ReviewPhotoSerializer(photo).data,
            status=status.HTTP_201_CREATED
        )

class ReviewPhotoListView(generics.ListAPIView):
    serializer_class = ReviewPhotoSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    
    def get_queryset(self):
        review_id = self.kwargs['pk']
        return ReviewPhoto.objects.filter(
            review_id=review_id,
            is_approved=True
        ).order_by('uploaded_at')
    
class VDJ_ReviewManagementView(APIView):
    """
    管理系统评价列表视图
    """
    def get(self, request):
        queryset = Review.objects.select_related('chef__user', 'customer', 'order').all()
        
        # 搜索条件
        chef_id = request.query_params.get('chef_id')
        chef_name = request.query_params.get('chef_name')
        chef_phone = request.query_params.get('chef_phone')
        is_public = request.query_params.get('is_public')
        
        if chef_id:
            queryset = queryset.filter(chef__id=chef_id)
        if chef_name:
            queryset = queryset.filter(
                Q(chef__user__username__icontains=chef_name) |
                Q(chef__user__first_name__icontains=chef_name) |
                Q(chef__user__last_name__icontains=chef_name)
            )
        if chef_phone:
            queryset = queryset.filter(chef__user__phone__icontains=chef_phone)
        if is_public:
            queryset = queryset.filter(is_public=is_public.lower() == 'true')
            
        serializer = ReviewSerializer(queryset, many=True)
        return Response({
            'results': serializer.data,
            'count': queryset.count()
        })

class VDJ_ReviewPhotoManagementView(APIView):
    """
    评价图片管理
    """
    def patch(self, request, pk):
        photo = get_object_or_404(ReviewPhoto, pk=pk)
        is_approved = request.data.get('is_approved')
        
        if is_approved is not None:
            photo.is_approved = is_approved
            if is_approved:
                photo.approved_by = request.user
            photo.save()
            return Response(ReviewPhotoSerializer(photo).data)
        
        return Response(
            {'error': '缺少is_approved参数'},
            status=status.HTTP_400_BAD_REQUEST
        )

    def delete(self, request, pk):
        photo = get_object_or_404(ReviewPhoto, pk=pk)
        photo.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)